<template>
  <uni-nav-bar title="任务" left-icon="left" @clickLeft="navBack" :fixed="true" statusBar></uni-nav-bar>
  <!-- 切换 -->
  <z-tabs ref="tabs" :list="list" :current="current" @change="tabsChange" inactive-color="#333" />
  <scroll-view scroll-y="true" enable-back-to-top @scrolltolower="loadMore" class="scroll-box"
    :style="{ height: pageHeight + 'px' }">
    <view class="package_sale space-between" v-if="current==2">
      <view>查看本次需要携带的所有福利品</view>
      <view class="bnt" @click="navTo('Sale/order/takeGood')">点击查看</view>
    </view>
    <view class="package_sale" v-for="item in orderList" :key="item.id">
      <view class="space-between">
        <view class="center">
          <text style="font-weight: 500;">订单号：{{item.order_sn}}</text>
          <!-- <text class="state">加急</text> -->
        </view>
        <view class="but">{{item.status_text?item.status_text:item.status_name}}</view>
      </view>
      <view class="center top">
        <view class="left">配送地址</view>
        <view class="center" style="align-items: flex-start;width:75%;">
          {{item.address?item.address:item.delivery_address}}
          <uni-icons type="navigate-filled" size="25" color="#999" style="margin-left:10rpx;margin-top:-5rpx;"
            @click="NavigationLoc(item)"></uni-icons>
        </view>
      </view>
      <view class="center top">
        <view class="left">预约时间</view>
        <view>{{item.deliverytime?item.deliverytime:item.delivery_time}}</view>
      </view>
      <view class="center top" v-if="item.endtime">
        <view class="left">送达时间</view>
        <view>{{item.endtime}}</view>
      </view>
      <view class="center top">
        <view class="left">车牌</view>
        <view>{{item.cart_code}}</view>
      </view>
      <view class="center top">
        <view class="left">车友</view>
        <view>{{item.driver_name}} <text style="color:#3F8FFB;"
            @click="telCall(item.driver_mobile)">{{item.driver_mobile}}</text></view>
      </view>
      <view class="center top">
        <view class="left">备注</view>
        <view class="center" style="width:70%;align-items: flex-start;">
          {{item.des?item.des:'备注'}}
          <uni-icons type="compose" size="18" style="margin-left:10rpx;" @click="operate(item.id,1)"
            v-if="current!==3"></uni-icons>
        </view>
      </view>
      <view class="center top">
        <view class="left">福利品</view>
        <view v-if="item.fuli_nums!=0" @click="current===0?operate(item.id,6):operate(item.subscribe_id,6)">
          {{item.fuli_nums}} >>
        </view>
        <view v-else>暂无福利品</view>
      </view>
      <view class="center top">
        <view class="left">进展</view>
        <view @click="operate(item.id,4,item.is_show)">{{item.status_text?item.status_text:item.status_name}}
          <uni-icons :type="item.is_show===1?'bottom':'top'" size="20"></uni-icons>
        </view>
      </view>
      <view class="center top" v-if="item.is_show===1">
        <view class="left"></view>
        <uni-section title="纵向排列" type="line" padding>
          <uni-steps :options="item.log_list" active-color="#007AFF" :active="active" direction="column" />
        </uni-section>
      </view>
      <view class="center bottoms">
        <view @click="operate(item.id,7)" v-if="!item.status">抢单</view>
        <view @click="operate(item.id,2,0,item.qrcode)" v-if="item.status==1||item.status==2">转单</view>
        <view @click="operate(item.id,3)" v-if="item.status==1">接单</view>
        <view @click="operate(item.id,5)" v-if="item.status==2">任务完成</view>
      </view>
    </view>
    <Popu v-if="orderList.length<1" :pageHeight="pageHeight" text="暂无任务"></Popu>
  </scroll-view>
  <!-- 导航 -->
  <uni-popup ref="Navigation" type="bottom" style="width:100%;">
    <view class="popup">
      <view class="" @click="daohang('bai')">百度地图</view>
      <view class="" @click="daohang('de')">高德地图</view>
      <view class="" @click="daohang('teng')">腾讯地图</view>
      <view class="" @click="() => Navigation.close()">取消</view>
    </view>
  </uni-popup>
  <!-- 选择时间弹框 -->
  <TimePicker ref="times" @confirm="confirm"></TimePicker>
  <!-- 留言 -->
  <Note @submit="submit" ref="notes"></Note>
  <!-- 确认转单人员弹框 -->
  <TransferOrder ref="transfer" :task_id="orderID" @berplate="tabsChange(1)"></TransferOrder>
  <!-- 转接单弹框 -->
  <ShiftPop ref="proposition" :task_id="appointment"></ShiftPop>
  <!-- 福利列表 -->
  <CarShop ref="shopList"></CarShop>
  <!-- 当前位置经纬度 -->
  <Lotlats @position="position"></Lotlats>
</template>

<script setup lang="ts">
  import { navBack, navTo } from '@/utils/navigator';
  import Popu from '@c/earthPushing/common/popu.vue';
  import TimePicker from '@c/earthPushing/bullet-box/timePicker.vue';
  import Lotlats from '@c/team/Lotlat.vue';
  import { ref } from 'vue';
  import { toPublish } from '@mqtt';
  import { telCall } from '@/utils/copyText';
  import CarShop from '@c/reservation/carShop.vue';
  import TransferOrder from '@c/reservation/transferOrder';
  import ShiftPop from '@c/reservation/shiftPop';
  import { getTaskList, getSubscribeLog } from '@/gql/earthPushing/dispatch';
  import { showLoading, errorToast, successToast } from '@/utils/prompt';
  import { onLoad } from '@dcloudio/uni-app';
  import Note from '@c/administrator/BulletBox/note.vue';
  import { getDriverID } from '@/stores/driverID';
  import { useUserInformation } from '@/stores/earthPushing/userSale';
  const userInfo = useUserInformation();
  const staff_id = getDriverID();
  const list = [{ name: '预约单', type: 99, badge: { count: 0 } }, { name: '新任务', type: 1 }, { name: '配送中', type: 2 }, { name: '已完成', type: 3 }]
  const active = 0 //纵向排列首位高亮
  const current = ref(0) //tab选中当前索引信息
  const tabs = ref(null) //tab切换组件
  const notes = ref(null) //留言弹框
  const transfer = ref(null) //确认转单人员弹框
  const Navigation = ref(null) //导航弹框
  const shopList = ref(null) //福利品列表弹框
  const proposition = ref(null) //存在转接单弹框
  const times = ref(null) //时间弹框
  const pageHeight = ref();

  const orderList = ref([])
  const lastPage = ref(1);
  const currentPage = ref(1);

  const type = ref(1)

  const orderID = ref() //选中的当前订单ID
  const taskID = ref()
  const longitude = ref()
  const latitude = ref()
  const orderAll = ref()

  const appointment = ref() //存在接单的订单ID
  const num = ref()
  uni.getSystemInfo({
    success: function (res) {
      pageHeight.value = res.windowHeight - 100;
    },
  });
  onLoad((pearm : any) => {
    taskID.value = pearm.task_id
  })
  init()
  function init() {
    if (current.value === 0) {
      reservation()
    } else {
      otherSta()
    }
  }
  // 预约单
  function reservation() {
    showLoading()
    const payload = {
      query: getSubscribeLog,
      variables: {
        page: currentPage.value,
        delivery_id: userInfo.delevery_id
      },
    };
    toPublish(
      'ql/staff/getSubscribeLog',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { getSubscribeLog } = obj.data;
        orderList.value = [...orderList.value, ...getSubscribeLog.list];
        lastPage.value = getSubscribeLog.lastpage;
      }
    );
  }
  // 已接单订单
  function otherSta() {
    showLoading()
    const payload = {
      query: getTaskList,
      variables: {
        page: currentPage.value,
        status: type.value,
        staff_id,
      },
    };
    toPublish(
      'ql/staff/getTaskList',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { getTaskList } = obj.data;
        orderList.value = [...orderList.value, ...getTaskList.list];
        lastPage.value = getTaskList.lastpage;
      }
    );
  }
  /**
   * 加载更多
   */
  function loadMore() {
    if (currentPage.value < lastPage.value) {
      currentPage.value++;
      init();
    }
  }
  function position(lat : number, lot : number) {
    longitude.value = lot;
    latitude.value = lat;
  }
  //tabs通知swiper切换
  function tabsChange(index : number) {
    Transfers()
    current.value = index;
    type.value = list[index].type
    currentPage.value = 1
    orderList.value = []
    init();
  }
  function operate(id : number, type : number, show : number, imsg : string) {
    orderID.value = id
    num.value = type
    switch (type) {
      case 1:
        notes.value.openBankPad();
        break;
      case 2:
        transfer.value.open();
        break;
      case 3:
        times.value.init()
        break;
      case 4:
        const num = show === 0 ? 1 : 0
        orderList.value.filter((item) => item.id === id ? item.is_show = num : item)
        break;
      case 5:
        complete()
        break;
      case 6:
        shopList.value.init(id)
        break;
      case 7:
        times.value.init()
        break;
    }
  }
  function confirm(time : any) {
    if (num.value === 7) {
      SeizeOrders(time)
    } else if (num.value === 3) {
      Receiving(time)
    }
  }
  // 抢单
  function SeizeOrders(e : any) {
    showLoading()
    const payload = {
      id: orderID.value,
      staff_id,
      endtime: e,
    };
    toPublish('staff/qiangSubscribeLog',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { code, msg } = obj;
        if (code === 1) {
          successToast(msg)
          setTimeout(() => {
            tabsChange(2)
          }, 1000)
        } else {
          errorToast(msg)
        }
      }
    );
  }
  // 接单
  function Receiving(e : any) {
    showLoading()
    const payload = {
      id: orderID.value,
      staff_id,
      endtime: e,
    };
    toPublish('staff/sureTask',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { code, msg } = obj;
        if (code === 1) {
          successToast(msg)
          setTimeout(() => { tabsChange(2) }, 1000)
        } else {
          errorToast(msg)
        }
      }
    );
  }
  // 备注
  function submit(note : string) {
    if (!note) {
      errorToast('暂无备注信息')
      return
    }
    showLoading()
    const payload = {
      id: orderID.value,
      des: note,
      staff_id
    };
    toPublish('staff/addDeliveryTaskDes',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { code, msg } = obj;
        if (code === 1) {
          successToast(msg)
          orderList.value = orderList.value.filter((item) => item.id === orderID.value ? item.des = note : item)
        } else {
          errorToast(msg)
        }
      }
    );
  }
  // 获取是否有接单信息
  Transfers()
  function Transfers() {
    showLoading()
    const payload = {
      staff_id
    };
    toPublish('staff/cehckZhuan',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { code, data } = obj;
        list[0].badge.count = data.count
        if (code === 1) {
          appointment.value = data.id
          proposition.value.open()
        }
      }
    );
  }
  // 已完成
  function complete() {
    showLoading()
    const payload = {
      id: orderID.value,
      staff_id
    };
    toPublish('staff/completeTask',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { code, msg } = obj;
        if (code === 1) {
          successToast(msg)
          setTimeout(() => {
            tabsChange(3)
          }, 1000)
        } else {
          errorToast(msg)
        }
      }
    );
  }
  // 导航并打开导航弹框
  function NavigationLoc(item : any) {
    orderAll.value = item
    Navigation.value.open()
  }
  function daohang(type : string) {
    let position = {
      latitude: Number(orderAll.value.latitude),
      longitude: Number(orderAll.value.longitude),
    };
    let addres = orderAll.value.address ? orderAll.value.address : orderAll.value.delivery_address;
    switch (type) {
      //高德地图高航
      case 'de':
        window.location.href = `https://uri.amap.com/navigation?from=${longitude.value},${latitude.value},当前位置&to=${orderAll.value.longitude
          },${orderAll.value.latitude},${addres}&mode=car&policy=1&src=${addres}&coordinate=gaode&callnative=1`;
        break;
      //百度地图导航
      case 'bai':
        window.location.href = `http://api.map.baidu.com/direction?origin=latlng:${latitude.value},${longitude.value
          }|name:当前位置&destination=${position}|name:${addres},&mode=driving&region=henan&output=html&src=webapp.baidu.openAPIdemo`;
        break;
      //腾讯地图导航
      case 'teng':
        window.location.href = `http://apis.map.qq.com/uri/v1/routeplan?type=drive&to=${addres}&tocoord=${position}&referer=dfdfd`;
        break;
    }
  }
</script>

<style scoped lang="less">
  .state {
    padding: 2rpx 10rpx;
    box-sizing: border-box;
    background: rgba(164, 202, 255, .3);
    border-radius: 30px;
    color: #3F8FFB;
    font-size: 24rpx;
    margin-left: 10rpx;
  }

  .top {
    margin-top: 15rpx;
    align-items: flex-start;

    .left {
      width: 22%;
      color: #666;
    }
  }

  .but {
    width: 140rpx;
    height: 57rpx;
    background: rgba(164, 202, 255, .2);
    border-radius: 5px;
    text-align: center;
    line-height: 50rpx;
    color: #3F8FFB;
  }

  .bottoms {
    justify-content: flex-end;
    margin-top: 20rpx;

    view {
      width: 166rpx;
      height: 64rpx;
      border: 1px solid #999999;
      border-radius: 5px;
      text-align: center;
      line-height: 64rpx;
      box-sizing: border-box;
      margin-left: 20rpx;
    }

    view:nth-of-type(3) {
      border: 0px;
      background: #1D8DFF;
      color: #fff;
    }
  }

  .popup {
    width: 100%;

    view {
      width: 100%;
      padding: 25rpx 0px;
      box-sizing: border-box;
      background-color: white;
      text-align: center;
      font-size: 32rpx;
    }

    view:nth-of-type(2) {
      border-bottom: 1px solid #eee;
      border-top: 1px solid #eee;
    }

    view:nth-last-child(1) {
      margin-top: 20rpx;
    }
  }

  .bnt {
    width: 108rpx;
    height: 36rpx;
    border: 1px solid #1B91FF;
    border-radius: 18rpx;
    text-align: center;
    line-height: 36rpx;
    font-size: 20rpx;
    color: #1D8DFF;
  }
</style>
<style>
  .top>>>.uni-steps__column-text {
    border-bottom: 0px;
  }

  .top>>>.uni-steps__column-title {
    font-size: 28rpx;
  }

  .top>>>.uni-steps__column-desc {
    font-size: 26rpx;
    margin-top: 5rpx;
  }

  .bottoms>>>.uni-date {
    width: 166rpx;
    flex: none;
  }
</style>